from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import os

from html import CheckBox, DropDown, MultiSelect, RadioButton #importing the html wrappers.
import validate #import validation
import tables
import main
import datetime
import staticInits 
import cgi #for escaping html chars in forms
import re


class AddMajor(webapp.RequestHandler):
    """
    This class deals with the admin add classes view.
    """

    
    def __init__(self):
        webapp.RequestHandler.__init__(self) #parent constructor call
        

        #DB CALLS
        self.majors = dict()
        
        #building dictionaries, keyed with name attributes which are gauranteed unique to each entry
        for row in db.GqlQuery("SELECT * FROM Major"): self.majors[row.name] = row

        
    def get(self):
        """
        Calls renderTemplate() for this class.
        """
        self.notValidated = dict()
        self.renderTemplate()

    def post(self):
        """
        Calls renderTemplate() for this class.
        """

        self.notValidated = dict()
        self.notValidated['major'] = ""


        clicked = self.request.get('submit', default_value="default")
            
        # adds this instructor to datastore and immediately displays it in instructor list
        if clicked == 'Add Major' :
            major = self.request.get('majorName')
            vMajor = validate.validateFreeText(major)
            uniqueMajor = validate.validateUniqueMajor(major)
            if vMajor and uniqueMajor : 
                newMajor = tables.Major( name = major )
                newMajor.put()
                self.majors[major] = major
            else : 
                if not vMajor: 
                    self.notValidated['major'] = major
                    self.response.out.write('<br><font color="red">Please enter a valid major.</font><br />')
                if not uniqueMajor:
                    self.notValidated['major'] = major
                    self.response.out.write('<br><font color="red">It appears that this major is already on the list. Please enter a unique major.</font><br />')

            
        self.__init__()
        self.renderTemplate()
    
    def renderTemplate(self, addValid = "") :
        """
        Renders the Template setup.html for this class.
        """

        sortedMajors = self.majors.keys()
        sortedMajors.sort(key = lambda x : x.lower())

        #setting up template dictionary
        templateValues = {
            #'table' : table
            'majors' : sortedMajors, 
            'badMajor' : self.notValidated['major'] if 'major' in self.notValidated else "",

            }


        #telling it to use the template
        path = os.path.join(os.path.dirname(__file__), 'addMajor.html')
        self.response.out.write(template.render(path, templateValues))



application = webapp.WSGIApplication([('/admin/addMajor', AddMajor)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

